var checkbox1 = document.createElement('input');
checkbox1.type = 'checkbox';
checkbox1.id = 'download_mode';
checkbox1.title = '下载模式：';
checkbox1.addEventListener('change', function(){
	if(checkbox1.checked)
		localStorage.setItem('downloadMode',1);
	else
		localStorage.setItem('downloadMode',0);
});

function getContent() {
	const now1 = new Date().getTime();
	var titleSelector = $('#title_id').val()
	var eSelector = $('#content_div_id').val();
	var d1 = $(eSelector);
	if (d1.length==0) {
		console.log("无法获取内容");
	}else{
		var title = "";
		try{
			title = $(titleSelector).text();
		}catch(e) {
			console.log(e)
		}
		var txt = "";
		for(var d of d1) {
			txt = txt + d.innerText + "\n";
		}
		var param = {content:title + "\n\n" + txt};
		if(checkbox1.checked){
			var req = new XMLHttpRequest();
			req.open('POST','http://localhost:8080/content');
			req.send(JSON.stringify( param ));
		}else{
			var blob1 = new Blob( [param.content], {type:'text/plain'} );
			//var down1 = document.createElement('a');
			//down1.download = `down-${now1}.txt`;
			//down1.href = window.URL.createObjectURL(blob1);
			//down1.click()

			chrome.runtime.sendMessage({
					action:"download",
					url:window.URL.createObjectURL(blob1)
				});
			console.log(window.URL.createObjectURL(blob1));
		}
		console.log("成功获取内容");
		localStorage.setItem('content_div_id', eSelector);
		localStorage.setItem('title_id',titleSelector);
	}
}

function guessContent2(element) {
	var ret = element;
	var maxlen = 0;
	for(var e=element.firstChild;e!=null && e!=undefined;e=e.nextSibling){
		if( e.tagName==='SCRIPT' || e.tagName==='STYLE'){
			continue;
		}
		if( e.tagName==='P' ){
			continue;
		}
		if( e.innerText===null || e.innerText===undefined ){
			continue;
		}
		if( e.innerText.length>maxlen && e.innerText.length>500 ){
			ret = e;
			maxlen = e.innerText.length
		}
	}

	if(ret===element)
		return ret;
	else
		return guessContent2(ret);
}

function elementInfo(element) {
	if(element.tagName===null){
		return "";
	}
	var ret = element.tagName+"[id:"+element.id+", class:"+element.className+"]  ";
	var e = element.parentElement;
	while(e!=null) {
		if(e.id.length>0)
			ret = e.tagName+"[#"+e.id+"]"+">"+ret;
		else if(e.className.length>0)
			ret = e.tagName+"[."+e.className+"]"+">"+ret;
		else
			ret = e.tagName+">"+ret;
		e = e.parentElement;
	}
	return ret;
}

var div = document.createElement('div');
div.id = "content_finder_plugin";
var moveTime = new Date();
var posY = 0;
function mouseIsStopEnough(){
	const now1 = new Date();
	if(now1.getTime()-moveTime.getTime() >= 5000) {
		//div.style = `width:100%;text-align: right;position: fixed;bottom:${posY}px;Z-INDEX:9999;background-color:#ffffff`;
		div.style["top"]=`${posY+10}px`;
	}
}

function handleDocumentClick(event) {
    var x = event.clientX, y = event.clientY;
    var element = document.elementFromPoint(x, y);
    var info = elementInfo(element);
    for(var e=element;e!=null;e=e.parentElement){
		if(e.id==="content_finder_plugin")
			return;
	}
    console.log(info); // 输出被点击的元素
    document.getElementById("element_clicked_info").innerText = info;
    moveTime = new Date();
    posY = y;
    setTimeout(mouseIsStopEnough,5000);
}

const mystyle = "{margin:5px;}";
const hidestyle = "display:none;";
const showstyle = "width:100%;text-align: right;position: fixed;top:0;Z-INDEX:9999;background-color:#ffffff";

div.style = hidestyle;

var guess1 = document.createElement('p');
guess1.innerText = "猜测(最大文本块):  "+elementInfo(guessContent2(document.body))+"  |";
div.appendChild(guess1);

var div1 = document.createElement("div");
div1.id = "element_clicked_info";
div1.innerText="";
div.appendChild(div1);

var buttonGetSelect = document.createElement('button');
buttonGetSelect.innerText = "保存被选内容";
buttonGetSelect.addEventListener('click', 
	(e)=>{ 
	//alert(document.getSelection().toString())
	var blob1 = new Blob( [document.getSelection().toString()], {type:'text/plain'} );

	chrome.runtime.sendMessage({
			action:"download",
			url:window.URL.createObjectURL(blob1)
		});	
	}
);
div.appendChild( buttonGetSelect );

var text1 = document.createElement('span');
text1.innerText = "  是否使用接收程序:";
div.appendChild(text1);

div.appendChild(checkbox1);

text1 = document.createElement('span');
text1.innerText = "  标题:  ";
div.appendChild(text1);

var titleId = document.createElement('input');
titleId.id = "title_id";
titleId.value = "h1";
titleId.style=mystyle;
div.appendChild(titleId);

var text2 = document.createElement('span');
text2.innerText = "  内容:  ";
div.appendChild(text2);

var input = document.createElement('input');
input.id="content_div_id";
input.value="test";
input.style=mystyle;
div.appendChild(input);

var next_txt  = document.createElement('span');
next_txt.innerText = "  下一章关键词:  ";
div.appendChild(next_txt);

var next_key = document.createElement('input');
next_key.id = 'next_keyword';
next_key.value = localStorage.getItem('next_keyword');
if(next_key.value==="")
	next_key.value = '下一章'
next_key.style = mystyle;
div.appendChild(next_key);

var bt = document.createElement('button');
bt.id="pick-content-button";
bt.onclick = getContent;
bt.innerHTML='[ 抓取 ]';
bt.style=mystyle;
div.appendChild(bt);

function autoPickContent(){
	var last = localStorage.getItem('last_pick_time');
	var now = new Date();
	if(now.getTime()-last < 30000) {
		localStorage.setItem('last_pick_time', now.getTime());
		getContent();
		var hrefs = $("a");
		localStorage.setItem('next_keyword', next_key.value);
		for(var i=0;i<hrefs.length;i++){
			if(hrefs[i].innerText === "下一章" || hrefs[i].innerText === "下一章节" || hrefs[i].innerText === next_key.value ){
				hrefs[i].click();
				break;
			}
		}
	}
}

var bt2 = document.createElement('button');
bt2.onclick = function(){
	var now = new Date();
	localStorage.setItem('last_pick_time', now.getTime());
	autoPickContent();
};
bt2.innerHTML='[ 自动 ]';
bt2.style=mystyle;
div.appendChild(bt2);

var bt3 = document.createElement('button');
bt3.onclick = function(){
	localStorage.setItem('last_pick_time', 0);
};
bt3.innerHTML='[ 停止自动抓取 ]';
bt3.style=mystyle;
div.appendChild(bt3);

document.body.insertBefore(div, document.body.firstChild);

var contentSelector = localStorage.getItem('content_div_id');
if(contentSelector===undefined || contentSelector===null){
	input.value = 'main';
	localStorage.setItem('content_div_id','main');
}else{
	input.value = contentSelector;
}

var titleSelector = localStorage.getItem('title_id');
if(titleSelector===undefined || titleSelector===null){
	titleId.value = "h1";
	localStorage.setItem('title_id','h1');
}else{
	titleId.value = titleSelector;
}

if(localStorage.getItem('downloadMode')==='1')
	checkbox1.checked = true;
else
	checkbox1.checked = false;

var mousePos = {x:0, y:0};

document.addEventListener('mousemove', (e)=>{
	mousePos.x = e.clientX;
	mousePos.y = e.clientY;
});
document.addEventListener(
	'keydown',
	(e) => {
		if( e.ctrlKey ) {
			let element = document.elementFromPoint( mousePos.x, mousePos.y );
			let info = elementInfo(element);
		    for(let e1=element;e!=null;e=e.parentElement){
				if(e1.id==="content_finder_plugin")
					return;
			}
		    console.log(info); // 输出被点击的元素
		    document.getElementById("element_clicked_info").innerText = info;
		}
	}
	);

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
	if (request.action === 'pluginShowHide') {
		if( request.text === "show" )
			div.style = showstyle;
		else if ( request.text === "hide" )
			div.style = hidestyle;
	} else if(request.action === 'pluginActionStop') {
		localStorage.setItem('last_pick_time', 0);
	}

  return true; // 保留消息通道打开，以便异步发送响应
});

setTimeout(autoPickContent, 2000);
